<template>
  <div class="questionnaire-preview">
    <!-- 问卷头部信息 -->
    <div class="header">
      <h2 class="title">{{ title || '问卷预览' }}</h2>
      <p class="description">{{ description || '暂无描述' }}</p>
    </div>

    <!-- 题目展示 -->
    <div v-if="questionsAndOptions.length > 0" class="questions-list">
      <div
        v-for="(item, index) in questionsAndOptions"
        :key="item.question.id || item.qid || index"
        class="question-row"
      >
        <div class="q-head">
          <span class="q-index">{{ index + 1 }}.</span>
          <span class="q-text">{{ item.question.content }}</span>
          <span v-if="item.question.required" class="q-required">*</span>
        </div>

        <!-- 单选 -->
        <el-radio-group
          v-if="item.question.type === 'radio'"
          v-model="answers[item.question.id]"
          class="control-group"
        >
          <div
            v-for="(opt, oIndex) in item.options"
            :key="opt.id || oIndex"
            class="option-line"
          >
            <el-radio :label="opt.id" class="ctrl">
              <span class="opt-text">{{ opt.optionContent }}</span>
            </el-radio>

            <el-input
              v-if="isOther(opt) && answers[item.question.id] === opt.id"
              v-model="otherAnswers[item.question.id]"
              placeholder="请输入其他内容"
              size="small"
              class="other-input"
            />
          </div>
        </el-radio-group>

        <!-- 多选 -->
        <el-checkbox-group
          v-else-if="item.question.type === 'checkbox'"
          v-model="answers[item.question.id]"
          class="control-group"
        >
          <div
            v-for="(opt, oIndex) in item.options"
            :key="opt.id || oIndex"
            class="option-line"
          >
            <el-checkbox :label="opt.id" class="ctrl">
              <span class="opt-text">{{ opt.optionContent }}</span>
            </el-checkbox>

            <el-input
              v-if="isOther(opt) && answers[item.question.id]?.includes(opt.id)"
              v-model="otherAnswers[item.question.id]"
              placeholder="请输入其他内容"
              size="small"
              class="other-input"
            />
          </div>
        </el-checkbox-group>

        <!-- 简答 -->
        <div v-else-if="item.question.type === 'text'" class="text-line">
          <el-input
            type="textarea"
            v-model="answers[item.question.id]"
            placeholder="请输入您的回答"
            :rows="3"
          />
        </div>
        <!-- 分隔线 -->
        <el-divider />
      </div>
    </div>

    <div v-else class="empty-text">暂无题目</div>

    <!-- 操作按钮 -->
    <div class="actions">
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const qid = route.params.id
const title = route.query.title || '未命名问卷'
const description = route.query.description || '暂无描述'

const questionsAndOptions = reactive([])
const answers = reactive({})
const otherAnswers = reactive({})

function goBack() {
  router.push('/HomePage/QuestionnaireList')
}

function isOther(opt) {
  if (!opt) return false
  if (opt.optionName && /other|OTHER|OTHER_OPTION|OTHER_FLAG/i.test(opt.optionName)) return true
  const txt = String(opt.optionContent || '').trim()
  return txt === '其他' || txt === '其它' || txt.includes('其他') || txt.includes('其它')
}

onMounted(() => {
  if (!qid) return
  request.get(`/question/listQuestionsByQid/${qid}`).then(res => {
    if (res.data.code === 200 && Array.isArray(res.data.data) && res.data.data.length > 0) {
      questionsAndOptions.splice(0, questionsAndOptions.length)

      const formatted = res.data.data.map(item => {
        const qidVal = item.qid
        const qIdField = item.question?.id || qidVal

        const opts = Array.isArray(item.options)
          ? item.options.map((opt, idx) => ({
              id: opt.id || `${qIdField}-opt-${idx}`,
              qid: opt.qid || qidVal,
              optionName: opt.optionName || '',
              optionContent: opt.optionContent || ''
            }))
          : []

        if (item.question?.type === 'checkbox') {
          answers[qIdField] = []
        } else {
          answers[qIdField] = ''
        }
        otherAnswers[qIdField] = ''

        return {
          qid: qidVal,
          question: {
            id: qIdField,
            qid: qidVal,
            content: item.question?.content || '',
            type: item.question?.type || 'radio',
            required: item.question?.required || false
          },
          options: opts
        }
      })

      questionsAndOptions.splice(0, questionsAndOptions.length, ...formatted)

      if (res.data.extra) {
        title.value = res.data.extra.title || title.value
        description.value = res.data.extra.description || description.value
      }

      ElMessage.success('问卷加载成功')
    } else {
      ElMessage.warning('未查询到问卷内容')
    }
  }).catch(err => {
    console.error(err)
    ElMessage.error('问卷加载失败')
  })
})
</script>

<style scoped>
.questionnaire-preview {
  max-width: 820px;
  margin: 0 auto;
  padding: 30px 24px 60px;
  color: #333;
  background: #fff;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}

/* === 头部（标题+描述） === */
.header {
  text-align: center;
  margin-bottom: 40px;
}
.title {
  font-size: 24px;
  font-weight: 600;
  color: #222;
  margin-bottom: 10px;
}
.description {
  font-size: 15px;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
  line-height: 1.6;
}

/* === 问题区域 === */
.questions-list {
  display: flex;
  flex-direction: column;
  gap: 26px;
}
.question-row {
  text-align: left;
}

/* 题头样式 */
.q-head {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  margin-bottom: 10px;
  font-size: 16px;
  color: #222;
  line-height: 1.6;
}
.q-index {
  color: #409eff;
  font-weight: 600;
}
.q-required {
  color: #ff4d4f;
  margin-left: 4px;
}

/* === 选项样式 === */
.control-group {
  display: block;
}
.option-line {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin: 6px 0;
}

.option-line ::v-deep(.el-radio),
.option-line ::v-deep(.el-checkbox) {
  display: flex;
  align-items: flex-start;
  width: 100%;
  margin: 0;
  padding: 0;
}
.option-line ::v-deep(.el-radio__input),
.option-line ::v-deep(.el-checkbox__input) {
  margin-right: 8px;
  margin-top: 4px;
}
.option-line ::v-deep(.el-radio__label),
.option-line ::v-deep(.el-checkbox__label) {
  white-space: normal;
  text-align: left;
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

/* 其他输入框 */
.other-input {
  margin-left: 12px;
  flex: 0 0 260px;
}

/* 简答题 */
.text-line {
  margin-top: 8px;
}

/* 空状态 */
.empty-text {
  text-align: center;
  color: #999;
  margin-top: 30px;
}

/* 底部按钮 */
.actions {
  text-align: center;
  margin-top: 50px;
}
</style>
